<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名:">
        <el-input placeholder="请输入搜索用户名" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            size="default"
            :disabled="!keyword"
            @click="search">
          搜索
        </el-button>
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <div class="operation-btns">
      <el-button type="primary" size="default" @click="addUser">
        添加用户
      </el-button>
      <el-button
          type="danger"
          size="default"
          :disabled="!selectIdArr.length"
          @click="deleteSelectUser"
      >
        批量删除
      </el-button>
    </div>
    <!-- table展示用户信息 -->
    <el-table
        @selection-change="selectChange"
        style="margin: 10px 0"
        border
        :data="filteredUserArr"
        v-loading="loading"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column
          label="序号"
          align="center"
          type="index"
          width="60"
          :index="indexMethod"
      ></el-table-column>
      <el-table-column
          label="ID"
          align="center"
          prop="id"
          width="80"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="用户名"
          align="center"
          prop="username"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="密码"
          align="center"
          prop="password"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="用户名称"
          align="center"
          prop="name"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="性别"
          align="center"
          width="60"
          prop="sex"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="年龄"
          align="center"
          width="60"
          prop="age"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="权限" align="center" width="100">
        <template #default="{ row }">
          <span v-if="row.role == 1"><el-tag type="success">会员</el-tag></span>
          <span v-else><el-tag type="info">非会员</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column
          label="地址"
          align="center"
          prop="address"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="创建时间"
          align="center"
          width="180"
          show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
          label="电话号码"
          align="center"
          prop="phone"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateUser(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
              :title="`确定要删除${row.name}吗?`"
              width="260px"
              @confirm="deleteUser(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
    />
  </el-card>
  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer" size="400px" :destroy-on-close="true">
    <!-- 头部标题 -->
    <template #header>
      <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input
              placeholder="请输入用户名"
              v-model="userParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              placeholder="请输入密码"
              v-model="userParams.password"
              type="password"
              show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <el-input
              placeholder="请输入用户名称"
              v-model="userParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="userParams.sex" placeholder="请选择用户性别" style="width: 100%">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户年龄" prop="age">
          <el-input-number
              placeholder="请输入用户年龄"
              :max="100"
              :min="1"
              v-model="userParams.age"
              style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="用户地址" prop="address">
          <el-select
              v-model="userParams.address"
              placeholder="请选择用户地址"
              style="width: 100%"
              filterable
          >
            <el-option
                v-for="item in provinceArr"
                :key="item.name"
                :label="item.value"
                :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户权限" prop="role">
          <el-select v-model="userParams.role" placeholder="请选择用户权限" style="width: 100%">
            <el-option label="会员" :value="1"></el-option>
            <el-option label="非会员" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户电话" prop="phone">
          <el-input
              placeholder="请输入用户电话"
              v-model="userParams.phone"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import useLayOutSettingStore from '@/store/modules/setting'
import { ref, onMounted, reactive, nextTick, computed } from 'vue'
import {
  reqSelectUser,
  reqRemoveUser,
  reqUserInfo,
  reqAddOrUpdateUser,
} from '@/api/user'
import type { User } from '@/api/user/type'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatTime } from '@/utils/time.ts'

// 页码和分页相关
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
let loading = ref<boolean>(false)

// 用户数据
let userArr = ref<User[]>([])

// 抽屉控制
let drawer = ref<boolean>(false)

// 用户参数
let userParams = reactive<User>({
  username: "",
  address: '',
  age: 0,
  createTime: [],
  id: 0,
  isExist: 0,
  login: '',
  phone: '',
  role: 0,
  name: '',
  sex: '',
  password: ''
})

// 批量删除选中的用户ID
let selectIdArr = ref<User[]>([])

// 中国省份数据
let provinceArr = ref<any>([
  { name: '北京市', value: '北京市' },
  { name: '天津市', value: '天津市' },
  { name: '上海市', value: '上海市' },
  { name: '重庆市', value: '重庆市' },
  { name: '河北省', value: '河北省' },
  { name: '河南省', value: '河南省' },
  { name: '云南省', value: '云南省' },
  { name: '辽宁省', value: '辽宁省' },
  { name: '黑龙江省', value: '黑龙江省' },
  { name: '湖南省', value: '湖南省' },
  { name: '安徽省', value: '安徽省' },
  { name: '山东省', value: '山东省' },
  { name: '新疆维吾尔自治区', value: '新疆维吾尔自治区' },
  { name: '江苏省', value: '江苏省' },
  { name: '浙江省', value: '浙江省' },
  { name: '江西省', value: '江西省' },
  { name: '湖北省', value: '湖北省' },
  { name: '广西壮族自治区', value: '广西壮族自治区' },
  { name: '甘肃省', value: '甘肃省' },
  { name: '山西省', value: '山西省' },
  { name: '内蒙古自治区', value: '内蒙古自治区' },
  { name: '陕西省', value: '陕西省' },
  { name: '吉林省', value: '吉林省' },
  { name: '福建省', value: '福建省' },
  { name: '贵州省', value: '贵州省' },
  { name: '广东省', value: '广东省' },
  { name: '青海省', value: '青海省' },
  { name: '西藏自治区', value: '西藏自治区' },
  { name: '四川省', value: '四川省' },
  { name: '宁夏自治区', value: '宁夏自治区' },
  { name: '海南', value: '海南' },
  { name: '台湾', value: '台湾' },
  { name: '香港', value: '香港' },
  { name: '澳门', value: '澳门' },
  { name: '海外', value: '海外' },
])

// 表单引用
let formRef = ref<any>()

// 搜索关键字
let keyword = ref<string>('')

// 设置仓库
let settingStore = useLayOutSettingStore()

// 过滤后的用户数据（用于搜索功能）
const filteredUserArr = computed(() => {
  const start = (pageNo.value - 1) * pageSize.value
  const end = start + pageSize.value
  
  // 如果有搜索关键字，先过滤数据
  const filtered = keyword.value
    ? userArr.value.filter(user => 
        user.username.toLowerCase().includes(keyword.value.toLowerCase()) ||
        user.name.toLowerCase().includes(keyword.value.toLowerCase()))
    : userArr.value
  
  // 更新总数
  total.value = filtered.length
  
  // 返回当前页的数据
  return filtered.slice(start, end)
})

// 序号计算方法
const indexMethod = (index: number) => {
  return (pageNo.value - 1) * pageSize.value + index + 1
}

// 组件挂载完毕获取用户数据
onMounted(() => {
  getHasUser()
})

// 获取用户数据
const getHasUser = async () => {
  loading.value = true
  try {
    let result: any = await reqUserInfo()
    if (Array.isArray(result)) {
      userArr.value = result
      total.value = result.length
    } else {
      ElMessage.error('获取用户数据失败')
    }
  } catch (error) {
    console.error('获取用户数据出错:', error)
    ElMessage.error('获取用户数据出错')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = () => {
  // 页码变化时不需要重新请求数据，因为我们使用的是前端分页
}

// 分页大小变化处理
const handleSizeChange = () => {
  // 重置页码为1
  pageNo.value = 1
}

// 添加用户
const addUser = () => {
  drawer.value = true
  // 清空数据
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: '',
    phone: '',
    sex: '',
    address: '',
    age: 0,
    role: 0,
  })
  // 清除上一次的错误提示
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 更新用户
const updateUser = (row: User) => {
  drawer.value = true
  // 存储用户信息
  Object.assign(userParams, row)
  // 清除上一次的错误提示
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 保存用户信息
const save = async () => {
  // 表单验证
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 显示加载状态
    loading.value = true
    
    // 添加或更新用户
    let result: any = await reqAddOrUpdateUser(userParams)
    
    if (result.code == 1) {
      // 关闭抽屉
      drawer.value = false
      
      // 提示消息
      ElMessage({
        type: 'success',
        message: userParams.id ? '更新成功' : '添加成功',
      })
      
      // 重新获取用户数据
      getHasUser()
    } else {
      ElMessage({
        type: 'error',
        message: userParams.id ? '更新失败' : '添加失败',
      })
    }
  } catch (error) {
    console.error('保存用户信息出错:', error)
    ElMessage.error('表单验证失败，请检查输入')
  } finally {
    loading.value = false
  }
}

// 取消按钮
const cancel = () => {
  drawer.value = false
}

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, message: '用户名至少5个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请选择地址', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '手机号必须是11位', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择用户权限', trigger: 'change' }
  ]
}

// 删除用户
const deleteUser = async (userId: number) => {
  try {
    loading.value = true
    let result: any = await reqRemoveUser(userId)
    if (result.code == 1) {
      ElMessage({type: 'success', message: '删除成功'})
      await getHasUser()
    } else {
      ElMessage({type: 'error', message: '删除失败'})
    }
  } catch (error) {
    console.error('删除用户出错:', error)
    ElMessage.error('删除用户出错')
  } finally {
    loading.value = false
  }
}

// 表格复选框选择变化
const selectChange = (value: User[]) => {
  selectIdArr.value = value
}

// 批量删除
const deleteSelectUser = async () => {
  if (!selectIdArr.value.length) return
  
  try {
    // 确认删除
    await ElMessageBox.confirm('确定要批量删除选中的用户吗？', '批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    // 整理批量删除的参数
    let idsList = selectIdArr.value.map(item => item.id)
    // 批量删除请求
    let result: any = await reqSelectUser(idsList)
    if (result.code == 200) {
      ElMessage({type: 'success', message: '批量删除成功'})
      await getHasUser()
    } else {
      ElMessage({type: 'error', message: '批量删除失败'})
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除出错:', error)
      ElMessage.error('批量删除出错')
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const search = () => {
  // 重置页码
  pageNo.value = 1
}

// 重置
const reset = () => {
  keyword.value = ''
  pageNo.value = 1
  settingStore.refresh = !settingStore.refresh
}
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-btns {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
}
</style>
